package com.weiwei.diancan.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.weiwei.diancan.Contant.Config;
import com.weiwei.diancan.R;
import com.weiwei.diancan.adapter.MainDetailAdapter;
import com.weiwei.diancan.adapter.MainTypeAdapter;
import com.weiwei.diancan.base.BaseActivity;
import com.weiwei.diancan.bean.LoginBean;
import com.weiwei.diancan.cache.CacheConfig;
import com.weiwei.diancan.utils.LoggerUtils;
import com.weiwei.diancan.view.HuanZhuoDialog;
import com.weiwei.diancan.view.LoginDialog;
import com.weiwei.diancan.view.PayPopwindow;
import com.weiwei.diancan.view.UpdateDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;

import weiwei.com.weiweilibrary.views.ToastUtil;

public class MainActivity extends BaseActivity {

    private PayPopwindow payPopwindow;
    private RecyclerView rv_type;
    private RecyclerView rv_detail;
    private MainTypeAdapter mainTypeAdapter;
    private MainDetailAdapter mainDetailAdapter;
    private UpdateDialog updateDialog;
    private LoginDialog loginDialog;
    private TextView all_order;
    private LinearLayout ll_main;

    private boolean isHuanZhuo = false; //记录是否处于换桌状态
    private HuanZhuoDialog huanZhuoDialog;
    private LoginBean info;
    private LinearLayoutManager mTeamsLayoutManager;
    private int oldSelectedPosition = 0;

    @Override
    public void getData() {


    }

    @Override
    public void setListeners() {
        /**
         * 全部订单
         */
        all_order.setOnClickListener(v -> {
            openActivity(AllOrderActivity.class,null);
        });

        /**
         * 餐桌分类
         */
        mainTypeAdapter.setOnRecyclerViewItemClickListener(
                (v,position,listData)->
                {
                    changeSelected(position);
                    moveToThisSortFirstItem(position);
                });

        /**
         * 餐桌详情
         */
        mainDetailAdapter.setOnItemClickListener((itemView, position, tabListBean) -> {

            if(isHuanZhuo){   //换桌操作
                if (!tabListBean.getTab_state().equals("1")) {  //暂停的餐桌
                    ToastUtil.showToast(MainActivity.this,"请选择空闲餐桌");
                } else {
                    huanZhuoDialog.show();
                }
            }else {
                if (tabListBean.getTab_state().equals("0")) {  //暂停的餐桌

                } else if (tabListBean.getTab_state().equals("1")) { //空闲的餐桌
                    updateDialog.setTabListBean(tabListBean);
                    updateDialog.getTv_message().setText("请输入"+tabListBean.getTab_name()+"上客人数");
                    updateDialog.getEt_num().setHint(tabListBean.getTab_name());
                    updateDialog.show();
                } else if (tabListBean.getTab_state().equals("2")) { //使用中的餐桌
                    openActivity(OrderDetailActivity.class, null);
                }
            }
        });



        /**
         * 开桌
         */
        updateDialog.setListener((v, text,tabListBean) -> {
            if(text.isEmpty()){
                ToastUtil.showToast(MainActivity.this,"请输入上客人数");
                return;
            }else{
                updateDialog.getEt_num().setText("");
                closeInput(updateDialog.getEt_num());

                Bundle bundle = new Bundle();
                bundle.putSerializable("tabListBean",tabListBean);
                openActivity(OpenActivity.class,bundle);
                updateDialog.cancel();
            }
        });

        /**
         * 换桌提示
         */
        huanZhuoDialog.setOnHZClick(v->{
            isHuanZhuo = false;  //重置换桌状态
            huanZhuoDialog.cancel();
        });

        /**
         * 联动效果
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            rv_detail.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    //第一个完全显示的item和最后一个item。
                    int firstVisibleItem = mTeamsLayoutManager.findFirstCompletelyVisibleItemPosition();
                    int lastVisibleItem = mTeamsLayoutManager.findLastVisibleItemPosition();
                    //此判断，避免左侧点击最后一个item无响应
                    if(lastVisibleItem != mTeamsLayoutManager.getItemCount()-1){
                        int sort = mainDetailAdapter.getSortType(firstVisibleItem);
                        changeSelected(sort);
                    }else {
                        changeSelected(mainTypeAdapter.getItemCount()-1);
                    }
                    if(needMove){
                        needMove = false;
                        //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                        int n = movePosition - mTeamsLayoutManager.findFirstVisibleItemPosition();
                        if ( 0 <= n && n < rv_detail.getChildCount()){
                            //获取要置顶的项顶部离RecyclerView顶部的距离
                            int top = rv_detail.getChildAt(n).getTop()-dip2px(MainActivity.this,28);
                            //最后的移动
                            rv_detail.scrollBy(0, top);
                        }
                    }
                }
            });
        }else {
            rv_detail.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    //第一个完全显示的item和最后一个item。
                    int firstVisibleItem = mTeamsLayoutManager.findFirstCompletelyVisibleItemPosition();
                    int lastVisibleItem = mTeamsLayoutManager.findLastVisibleItemPosition();
                    //此判断，避免左侧点击最后一个item无响应
                    if(lastVisibleItem != mTeamsLayoutManager.getItemCount()-1){
                        int sort = mainDetailAdapter.getSortType(firstVisibleItem);
                        changeSelected(sort);
                    }else {
                        changeSelected(mainTypeAdapter.getItemCount()-1);
                    }
                    if(needMove){
                        needMove = false;
                        //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                        int n = movePosition - mTeamsLayoutManager.findFirstVisibleItemPosition();
                        if ( 0 <= n && n < rv_detail.getChildCount()){
                            //获取要置顶的项顶部离RecyclerView顶部的距离
                            int top = rv_detail.getChildAt(n).getTop()-dip2px(MainActivity.this,28);
                            //最后的移动
                            rv_detail.scrollBy(0, top);
                        }
                    }
                }
            });
        }

    }

    private boolean needMove=false;
    private int movePosition;
    private void moveToPosition(int n) {
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        int firstItem = mTeamsLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mTeamsLayoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (n <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            rv_detail.scrollToPosition(n);
        } else if (n <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            int top = rv_detail.getChildAt(n - firstItem).getTop();
            rv_detail.scrollBy(0, top - dip2px(this, 28));
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            rv_detail.scrollToPosition(n);
            movePosition = n;
            needMove = true;
        }
    }

    private void moveToThisSortFirstItem(int position) {
        movePosition = 0;
        for(int i=0;i<position;i++){
            movePosition += mainDetailAdapter.getCategoryList().get(i).getTab_list().size();
        }
        moveToPosition(movePosition);
    }

    private void changeSelected(int position) {
        Log.e("tag","position:"+position);
        List<LoginBean.TypeListBean> data = mainTypeAdapter.getData();
        data.get(oldSelectedPosition).setSelect(false);
        data.get(position).setSelect(true);
        //增加左侧联动
        rv_type.scrollToPosition(position);
        oldSelectedPosition = position;
        mainTypeAdapter.notifyDataSetChanged();
    }

    /**
     * 根据手机分辨率从dp转成px
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return(int) (dpValue * scale + 0.5f);
    }

    @Override
    public void initView() {

        List<LoginBean.TypeListBean> list = new ArrayList<>();

        all_order = (TextView)findViewById(R.id.all_order);

        mainTypeAdapter = new MainTypeAdapter(list,this);
        rv_type = (RecyclerView)findViewById(R.id.rv_type);
        rv_type.setLayoutManager(new LinearLayoutManager(this));
        rv_type.setAdapter(mainTypeAdapter);

        mainDetailAdapter = new MainDetailAdapter(this,list);
        rv_detail = (RecyclerView)findViewById(R.id.rv_detail);
        mTeamsLayoutManager = new LinearLayoutManager(this);
        rv_detail.setLayoutManager(mTeamsLayoutManager);
        rv_detail.setAdapter(mainDetailAdapter);
        StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(mainDetailAdapter);
        rv_detail.addItemDecoration(headersDecor);


        updateDialog = new UpdateDialog(this);
        updateDialog.getTv_title().setText("开桌");

        ll_main = (LinearLayout)findViewById(R.id.ll_main);

    }

    @Override
    public void initTitle() {
        initPop();
        huanZhuoDialog = new HuanZhuoDialog(this);
        loginDialog = new LoginDialog(this);
        titler.setText("御膳府");
        iv.setVisibility(View.VISIBLE);
        iv.setOnClickListener(v->{
            backgroundAlpaha(this,0.5f);
            payPopwindow.showAsDropDown(iv);
        });

    }

    @Subscribe
    public void onEvent(String s){
        if(s.equals(Config.KAIZHUO)){  //换桌
            isHuanZhuo = true;
        }
    }

    @Subscribe
    public void onLogin(LoginBean loginBean){
        info = loginBean;
        if(info!=null){
                info.getType_list().get(0).setSelect(true);
        }
        LoggerUtils.loge("token:"+CacheConfig.getInst().getToken(this));
        mainTypeAdapter.setNewData(info.getType_list());
        mainDetailAdapter.setCategoryList(info.getType_list());
    }


    /**
     * 设置添加屏幕的背景透明度
     * **/
    public void backgroundAlpaha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow()
                .addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }

    @Override
    public void setLayoutView() {
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void initPop() {
        payPopwindow = new PayPopwindow(this);
        payPopwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpaha(MainActivity.this,1f);
            }
        });
        payPopwindow.setOnItemClick(index->{
                switch (index){
                    case 0:
                        loginDialog.show();
                        payPopwindow.dismiss();
                        break;
                    case 1:
                        openActivity(LoginActivity.class,null);
                        payPopwindow.dismiss();
                        break;
                    case 2:
                        openActivity(PessmiseActivity.class,null);
                        payPopwindow.dismiss();
                        break;
                }
        });
    }
}
